package com.cn.kehong.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetworkUtil {

    public static String getArpCache() throws Exception {
        Process process = Runtime.getRuntime().exec("arp -a");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n"); // 读取每一行
        }

        reader.close();
        return output.toString(); // 返回ARP缓存的内容
    }

    public static String getMacAddressByIp(String ip) throws Exception {
        String arpCache = getArpCache();
        String macAddress = null;

        // 定义正则表达式匹配MAC地址
        Pattern pattern = Pattern.compile(ip + "\\s+([a-fA-F0-9\\-]{17}|[a-fA-F0-9]{2}([\\s:]?[a-fA-F0-9]{2}){5})");
        Matcher matcher = pattern.matcher(arpCache);

        if (matcher.find()) {
            macAddress = matcher.group(1); // 获取MAC地址
        }

        return macAddress; // 返回MAC地址
    }

    public static String getMacAddrByIp(String ip) {
        String macAddr = null;
        try {
            Process process = Runtime.getRuntime().exec("nbtstat -a " + ip);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            Pattern pattern = Pattern.compile("([A-F0-9]{2}-){5}[A-F0-9]{2}");
            Matcher matcher;
            for (String strLine = br.readLine(); strLine != null;
                 strLine = br.readLine()) {
                matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    macAddr = matcher.group();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return macAddr;
    }
}
